package com.zjb.demo.system.controller;

import cn.hutool.core.util.StrUtil;
import com.zjb.demo.common.config.AppConfig;
import com.zjb.demo.common.constant.MimeTypeConstants;
import com.zjb.demo.common.domain.response.AjaxResult;
import com.zjb.demo.common.exception.AuthException;
import com.zjb.demo.common.util.FileUtils;
import com.zjb.demo.common.util.SecurityUtils;
import com.zjb.demo.system.domain.User;
import com.zjb.demo.system.domain.vo.ProfileVo;
import com.zjb.demo.system.service.TokenService;
import com.zjb.demo.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.UploadedFile;

import java.io.File;
import java.io.IOException;
import java.util.Optional;

/**
 * @author 庄佳彬
 * @since 2023/12/30 23:12
 */
@Controller
@Mapping("/system/user/profile")
@Api(tags = "个人信息 业务处理")
public class SysProfileController {
    @Inject
    private UserService userService;
    @Inject
    private TokenService tokenService;
    @Inject
    private AppConfig appConfig;

    @Get
    @Mapping
    @ApiOperation(value = "个人信息")
    public AjaxResult<ProfileVo> profile() {
        var loginUser = SecurityUtils.getLoginUser()
                .orElseThrow(AuthException::new);
        var roleGroup = userService.selectUserRoleGroup(loginUser.getUsername());
        var postGroup = userService.selectUserPostGroup(loginUser.getUsername());
        return AjaxResult.success(new ProfileVo(loginUser.getUser(), roleGroup, postGroup));
    }

    @Put
    @Mapping
    @ApiOperation(value = "修改个人信息")
    public AjaxResult<Void> updateProfile(@Body User user) {
        var loginUser = SecurityUtils.getLoginUser()
                .orElseThrow(AuthException::new);
        var sysUser = loginUser.getUser();
        if (StrUtil.isNotEmpty(user.getPhoneNumber()) && userService.existsByPhone(user.getPhoneNumber())) {
            return AjaxResult.fail("手机号已存在");
        }
        if (StrUtil.isNotEmpty(user.getEmail()) && userService.existsByEmail(user.getEmail())) {
            return AjaxResult.fail("邮箱已存在");
        }
        user.setId(sysUser.getId());
        user.setPassword(null);
        user.setDeptId(null);
        user.setAvatar(null);
        if (userService.updateById(user)) {
            sysUser.setNickName(user.getNickName());
            sysUser.setPhoneNumber(user.getPhoneNumber());
            sysUser.setEmail(user.getEmail());
            tokenService.setLoginUser(() -> Optional.of(loginUser));
            return AjaxResult.success();

        }
        return AjaxResult.fail("修改个人信息异常，请联系管理员");
    }

    @Put
    @Mapping("/updatePwd")
    @ApiOperation(value = "重置密码")
    public AjaxResult<Void> updatePwd(String oldPassword, String newPassword) {
        var loginUser = SecurityUtils.getLoginUser()
                .orElseThrow(AuthException::new);
        var userName = loginUser.getUsername();
        var password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return AjaxResult.fail("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return AjaxResult.fail("新密码不能与旧密码相同");
        }
        var pwd = SecurityUtils.encryptPassword(newPassword);
        if (userService.resetUserPwd(userName, pwd)) {
            loginUser.getUser().setPassword(pwd);
            tokenService.setLoginUser(() -> Optional.of(loginUser));
            return AjaxResult.success();

        }
        return AjaxResult.fail("修改密码异常，请联系管理员");
    }

    @Post
    @Mapping("/avatar")
    @ApiOperation(value = "修改头像")
    public AjaxResult<String> updateAvatar(UploadedFile file) throws IOException {
        var loginUser = SecurityUtils.getLoginUser()
                .orElseThrow(AuthException::new);
        if (!file.isEmpty()) {
            var localPath = appConfig.getLocalFilePath() + "/avatar/";
            FileUtils.assertAllowed(file.getName(), MimeTypeConstants.DEFAULT_ALLOWED_EXTENSION);
            file.transferTo(new File(localPath + file.getName()));
            String avatar = "/upload/avatar/" + file.getName();
            if (userService.updateAvatar(loginUser.getUsername(), avatar)) {
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(() -> Optional.of(loginUser));
                return AjaxResult.success();
            }
        }
        return AjaxResult.fail("上传图片异常，请联系管理员");

    }
}
